<template>
  <div id="app" v-bind:style="appDivStyle">
      <div class="context" ref="context">
           <div class="queryBox" ref="queryBox">
                <el-form :model="formQueryCondition"
                         ref="form" size="mini">
                    <el-row>
                      <!-- 标签名称 -->
                      <el-col :span="7">
                        <el-form-item :label="$t('tagManage.queryLabel.tagName')"
                        :label-width="queryformLabelWidth">
                            <el-input v-model.trim="formQueryCondition.tagName.val" class="queryItemStyle" clearable
                                      :placeholder="$t('tagManage.queryLabel.placeholderTagName')"></el-input>
                        </el-form-item>
                      </el-col>
                      <!-- 上线状态 -->
                      <el-col :span="7" :offset="1">
                        <el-form-item :label="$t('tagManage.queryLabel.status')"   :label-width="queryformLabelWidth">
                            <el-select v-model="formQueryCondition.state.val" class="queryItemStyle">
                              <el-option :label="$t('tagManage.label.all')" value=""></el-option>
                              <el-option :value="drug.valueCode" :key="drug.valueCode" :label="drug.valueText" v-for="drug in enables"></el-option>
                              <!-- <el-option :label="$t('tagManage.label.online')" value="Online"></el-option>
                              <el-option :label="$t('tagManage.label.offline')" value="Offline"></el-option> -->
                            </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="24">
                        <div style="text-align:right">
                            <el-form-item>
                                <el-button type="primary" @click="onConfirm(temporaryReception)">{{ $t('btnText.confirmBtnText') }}</el-button>
                            <!-- </el-form-item> -->
                            <!-- <el-form-item> -->
                                <el-button type="primary" @click="onReset">{{ $t('btnText.resetBtnText') }}</el-button>
                            <!-- </el-form-item> -->
                            <!-- <el-form-item> -->
                                <el-button type="primary" @click="onQuery" icon="el-icon-search" :loading="loading">{{ $t('btnText.queryBtnText') }}</el-button>
                            </el-form-item>
                        </div>
                      </el-col>
                    </el-row>
                    <div style="text-align:left">
                    <!--当前选择&nbsp;&nbsp;{{tableChecked.length}}&nbsp;&nbsp;条数据-->{{ $t('tagManage.label.haveChosen') }}
                        <el-tag size="medium" :key="tag.keyId" v-for="tag in temporaryReception" :disable-transitions="false">
                          {{tag.tagName}}
                        </el-tag>
                    </div>
                </el-form>
            </div>
            <div class="dataBox" ref="dataBox">
                <!-- :row-key="getRowKeys" -->
                <!-- :reserve-selection="true" -->
                <transition enter-active-class="animated zoomIn" leave-active-class="animated rotateOut">
                    <el-table v-if="isInit" ref="singleTable"
                                :data="tableData"
                                :height="tableHeight"
                                class="jySelectionAll" 
                                 @select="handleSelectionChange"
                                @sort-change="sortChange"
                                v-loading="loading" size="mini"
                                style="width: 100%;" stripe=stripe border=border>
                         <!--复选框-->
                        <el-table-column type="selection"  width="50" fixed="left"  
                                            :label="$t('table.xh')" align="center">
                                            </el-table-column>
                        <el-table-column prop="tagName" min-width="180" fixed="left"
                                            :label="$t('tagManage.tableText.tagName')" sortable="custom" sort-by="TagName">
                        </el-table-column>
                        <el-table-column prop="assetNum" min-width="110" fixed="left"
                                            :label="$t('tagManage.tableText.assetsNum')" sortable="custom" sort-by="assetNum">
                        </el-table-column>
                        <el-table-column prop="state" min-width="130"
                        :label="$t('tagManage.tableText.status')" sortable="custom" sort-by="state">
                        </el-table-column>
                        <el-table-column prop="createdDate" min-width="180"
                        :label="$t('tagManage.tableText.createTime')" sortable="custom" sort-by="createdDate">
                        </el-table-column>
                        <el-table-column :label="$t('tagManage.tableText.lastUpdateBy')" min-width="120" sortable="custom" prop="modifier" sort-by="modifier">
                        </el-table-column>
                        <el-table-column :label="$t('tagManage.tableText.lastUpdateTime')" min-width="180" sortable="custom" prop="lastUpdatedDate" sort-by="lastUpdatedDate">
                        </el-table-column>

                    </el-table>
                </transition>

            </div>
        </div>
        <br>
        <div class="pageBox">
            <el-pagination @size-change="sizeChange"
                            @current-change="currentPageChange"
                            :current-page="pager.curPage"
                            :page-sizes="pager.sizes"
                            :page-size="pager.curSize"
                            :background="true"
                            layout="total, sizes, prev, pager, next, jumper" :total="pager.total">
            </el-pagination>
        </div>
  </div>
</template>

<script>

import comBaseVue from '../../baseViewModel';
import { futimes } from 'fs';
import { lt } from 'semver';

export default {
  mixins: [comBaseVue],
  name:'TagManage',
  components: {
    'upload-file': () => import('../common/UploadFile')
  },
  props:{
    menuCode:String,
    datas:{
      isClear: String,
      transmitDataLabel:null
    }
  },
  data () {

    return {
        isInit:false,
        tableHeight:100,
        isShowChoose:false,
        isShowEditForm2:false,
        enables:[],
        temporaryReception:[],
        appDivStyle:{
            height:this.$store.getters.appHeight,
        },
        dataDisplay:[], //数据回显
        modelName:"com.ispr.iptv.entity.media.SysTagEntity",
        // 查询条件
        formQueryCondition: {
            tagName: {

                //mapName: 'code.key',  映射的别名 在同时查询一个属性时需要别名
                //gName:'code',   组名
                key:'tagName',
                op: 'LIKE', // 操作符
                val: '' // 查询的值
            },
            state: {
               op: '=',
               key:'state',
                val: ''
            },
            isEnable:{
              key:'isEnable',
              op: '=',
              val:'Available'
            }
        },
        tableChecked:[],

    }
  },
  methods:{

     // 确定
    onConfirm:function(rows){
        // alert(1111);
        let tags = [];
        rows.forEach(element =>{
            tags.push({"tagName":element.tagName,"tagId":element.keyId});
        });
        // this.transmitDataLabel = [];
        this.$emit("tagChoose",tags,this.isShowChoose);
          
    },
  
     // 重置
    onReset:function(){
        if (this.$refs['form']) {
            this.$refs['form'].resetFields();
        }
        this.formQueryCondition.tagName.val = "";
        this.formQueryCondition.state.val = "";
        // this.formQueryCondition.sort.val = "";
    },
    // 新增
    onNew: function() {
        this.isShowEditForm = true;
        if (this.$refs['editForm']) {
            this.$refs['editForm'].resetFields();
        }
        this.editForm.keyId = "";
        this.editForm.version = "";
        this.editForm.tagName = "";
        // this.editForm.assetNum = "";
        this.editForm.state = "Online";
        this.curCommand = "SaveNewReturnPK";
        this.canEditCode = false;
    },

    //编辑面板提交后调用，设置唯一性验证条件
    setEditFormCheck:function setEditFormCheck(){
        if(this.curCommand == "SaveNewReturnPK"){
            this.editFormCheck = [{
                    key: 'tagName',
                    op: '=', // 操作符
                    val: this.editForm.tagName// 查询的值
                },{
                    key: 'isEnable',
                    op: '=', // 操作符
                    val: 'Available'
                }];
        }else if(this.curCommand == "PartialUpdateProc"){
            this.editFormCheck = [{
                    key: 'tagName',
                    op: '=', // 操作符
                    val: this.editForm.tagName// 查询的值
                },{
                    key: 'isEnable',
                    op: '=', // 操作符
                    val: 'Available'
                },{
                    key: 'keyId',
                    op: '<>', // 操作符
                    val: this.editForm.keyId
                }];
        }

    },

    // 编辑按钮回调事件
    editCallback: function(isSuccess,json) {
        if(isSuccess){
            this.curCommand = "PartialUpdateProc";
            this.isShowEditForm = true;
            if (this.$refs['editForm']) {
                this.$refs['editForm'].resetFields();
            }
            this.editForm.keyId = json.keyId;
            this.editForm.version = json.version;
            this.editForm.tagName = json.tagName;
            this.editForm.state = json.state;
            // this.canEditCode = true;
        }
        else{
            this.$message({
                message: json.msg,
                type: 'warning'
                });
        }
    },


    // // 批量下发
    // onBatchRelease: function(){
    //     this.isShowEditForm2 = true;
    // },
    //  // 提交编辑面板数据
    //     submitForm2: function submitForm2(formName) {
    //         var _this = this;

    //         this.$refs[formName].validate(function (valid) {
    //             if (valid) {
    //                 _this.loading = true;
    //                 _this.procCommand(_this.curCommand,
    //                 _this.modelName,
    //                 "Default",
    //                 _this.editForm,
    //                 _this.submitForm2Callback);
    //             } else {
    //                 return false;
    //             }
    //         });
    //     },
    //     // 执行命令后的回调函数
    //     submitForm2Callback: function submitForm2Callback(isSuccess,json) {
    //         this.loading = false;
    //         if(isSuccess){
    //             this.isShowEditForm2 = false;
    //             this.$message({
    //                 message: this.$i18n.t("message.successTip"),//resource.message.successTip,
    //                 type: 'success'
    //             });
    //             this.queryTable();
    //         }
    //         else
    //         {
    //             this.$message({
    //                             message: this.$i18n.t("errorCode." + json.reason),
    //                             type: 'warning'
    //                             });
    //         }
    //     },

     /////下载导入模板
    downloadTemplate: function downloadTemplate () {
      this.downloadByIdOrName(this, '/import/downtemplate', 'fileName', '标签信息导入模板.xlsx', '标签信息导入模板.xlsx');
    },

     /////////////////////////////////// 频道信息导入 ///////////////////////////////////////////
    // 打开导入资材关系的dialog
    openUploadDlg: function openUploadDlg () {
      let _this = this;
      this.$alert('注意：导入后将会覆盖原有的所有数据，是否继续？', '提示', {
        confirmButtonText: '确定',
        callback: action => {
          if (action === 'confirm') {
            // 初始化错误文件下载id
            _this.errorTaskId = null;
            // 清空文件列表
            _this.fileList = [];
            _this.dlgUploadVisible = true;
            // this.uploadPhorderUrl = this.baseUrl+'/import/upload';
            _this.uploadCourseMaterialParams = {'className': _this.modelName};
          }
        }
      });
    },

    submitUploadSuccess: function submitUploadSuccess (response, file, fileList) {
      if (response.code === 'SUCCESS') {
        if (response.data.status === '0') {
          this.dlgUploadVisible = false;
          this.$message.success('导入成功');
          this.fileList = []; // 清空上传文件列表
          // 刷新表格数据
          this.onQuery();
          return false;
        }
        if (response.data.status === '3') {
          let _this = this;
          this.$alert('导入失败，是否下载失败原因文件?', '提示', {
            confirmButtonText: '确定',
            callback: function callback (action) {
              if (action === 'confirm') {
                _this.downloadByIdOrName(_this, '/import/downerr', 'taskId', response.data.taskId, response.data.errFileName);
              } else {
                _this.$message({
                  type: 'info',
                  message: '已取消'
                });
              }
            }
          });
          this.fileList = []; // 清空上传文件列表
          this.dlgUploadVisible = false;
        }
      } else {
        this.$message.error(response.msg);
      }
    },
//////////////////////////////////////////////////////////////////////////////////////////////////

    // 导出
     onExport:function onExport () {
      let param = { 'className': 'com.ispr.iptv.entity.media.SysTagEntity', 'opKey': 'Export', 'params': [{ 'key': 'keyId', 'value': "", 'op': '=', 'group': 'allocateDemandId' }], 'sort': [{ 'col': 'keyId', 'order': 'desc' }], 'fileName': '调配资材' };
      let fileName = '标签管理' + '.xlsx';
      this.downloadByIdOrName(this, '/file/export', 'param', JSON.stringify(param), fileName);
    },

    //为状态下拉框赋值
    findEnables:function(){
      this.findByTypeCode("10006",this.setEnables);//根据类型编码去取相应的值
    },
    //下拉框值的回调
    setEnables:function(isSuccess,json){
      try{
        if(isSuccess){
          this.enables=[];
          for(var i=0 ; i < json.data.length ; i++){
            this.enables.push(json.data[i]);
          }
        }else{
          this.$message.error(json.msg);
        }
      }catch(e){
        alert(e);
      }
    },

    // getRowKeys(row) {
    //   return row.keyId;
    // },

    transmitData:function(transmitDataLabel){
      // debugger
      this.temporaryReception = JSON.parse(JSON.stringify(transmitDataLabel));
      // console.log('this.datas.transmitDataLabel============>',this.datas.transmitDataLabel);
      // console.log('temporaryReception============>',this.temporaryReception);
    },
    // 查询网格数据
    queryTable: function() {

      this.loading = true;
      this.queryModel(
        this.modelName,
        "Query",
        this.formQueryCondition,
        this.pager,
        this.sort,
        this.setTableData
      );
    },
     // 查询网格数据成功后的回调
        setTableData: function(isSuccess,json) {
            this.currentResCode = '';
            this.loading = false;
            try{
                if (isSuccess) {
                    //alert(JSON.stringify(json));
                    this.pager.total = json.total;
                    this.tableData = [];
                    this.datas.isClear = "false";
                    for (var i = 0; i < json.list.length; i++) {
                        this.tableData.push(json.list[i]);
                    }
                    // debugger
                    // console.log('this.datas.transmitDataLabel==>',this.datas.transmitDataLabel)
                    // debugger
                    // this.temporaryReception = JSON.parse(JSON.stringify(this.datas.transmitDataLabel));
                    if(this.temporaryReception.length > 0){
                      
                       let _this = this;
                        // dataDisplay 临时数据存储  tableChecked
                        this.dataDisplay = [];
                        // tableData存储全部数据
                        // tableChecked为父组件传递过来的数据
                        // this.temporaryReception = this.datas.transmitDataLabel;
                        for(let i=0;i<this.tableData.length;i++){
                          for(let n = 0;n<this.temporaryReception.length;n++){
                            if(this.tableData[i].keyId === this.temporaryReception[n].keyId){
                              // this.dataDisplayIsEnabled = false;
                              this.dataDisplay.push(this.tableData[i]); 
                            }
                          }
                        }
                        if(this.dataDisplay.length > 0){
                        this.$nextTick(function(){
                          for(let i = 0;i<this.dataDisplay.length;i++){
                            this.$refs.singleTable.toggleRowSelection(this.dataDisplay[i],true);
                          }
                        })   
                      }
                    }
                   
                   
                }
                else {
                    this.$message.error(json.msg);
                }
            }
            catch(e){
                alert(e);
            }
        },

    handleSelectionChange(selection,val) {
      // debugger
         // 判断当前点击的是打钩还是取消打钩 true 则是打勾
        let isSelected = this.isExistRow(selection, val, 'keyId');
        if(isSelected){
          // if (!this.isExistRow(this.tableChecked, val, 'keyId')) {
          //   this.tableChecked.push(val);
          // }
          // 勾选
            if(this.temporaryReception !== undefined){
              if (!this.isExistRow(this.temporaryReception, val, 'keyId')) {
                this.temporaryReception.push(val);
              }
            }
        }else {
            // 取消勾选
            for (let i in this.temporaryReception) {
              if (this.temporaryReception[i].keyId === val.keyId) {
                this.temporaryReception.splice(i, 1);
              }
            }
          }
        
      },
      // 判断 arrs数组中是否存在row 存在则返回true
    isExistRow: function isExistRow (arrs, row, field) {
      let flag = false;
      arrs.forEach(function (item) {
        if (row[field] === item[field]) {
          flag = true;
        }
      });
      return flag;
    },

    //  setTableData: function(isSuccess,json) {
            
    //         if(this.datas.isClear === "true"){
    //           this.tableChecked = [];
    //           this.$refs.singleTable.clearSelection();
    //           }
            
    //         this.currentResCode = '';
    //         this.loading = false;
            
    //         try{
    //             if (isSuccess) {
    //                 //alert(JSON.stringify(json));
    //                 this.pager.total = json.total;
    //                 this.tableData = [];
    //                 this.datas.isClear = "false";
    //                 for (var i = 0; i < json.list.length; i++) {
    //                     this.tableData.push(json.list[i]);
    //                 }
    //                 // this.datas.isClear = false;
                    
    //             }
    //             else {
    //                 this.$message.error(this.$i18n.t("errorCode." + json.reason,json.message));
    //             }
    //         }
    //         catch(e){
    //             alert(e);
    //         }
    //     },


  },
  mounted: function mounted() {
    
    this.transmitData(this.datas.transmitDataLabel);
    this.findEnables();
    this.tableHeight = this.$refs.context.offsetHeight - this.$refs.queryBox.offsetHeight;
    this.isInit = true;
    this.onQuery();
  }
}


</script>
<style>
/* 隐藏网格的全选按钮 */
.jySelectionAll >.el-table__fixed>.el-table__fixed-header-wrapper>.el-table__header> thead >tr>th >.cell>label {
  display: none;
}
/* 隐藏网格的全选按钮 */
.jySelectionAll >.el-table__header-wrapper>.el-table__header> thead >tr>th >.cell >label {
  display: none !important;
}
</style>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>
